#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include "Err.hpp"
#include "LogMessage.hpp"

static const int defaultepfd = -1;
static const int size = 128;
static const int num = 1024;

class Epoll
{
public:
    Epoll() : epfd_(defaultepfd)
    {
    }
    ~Epoll()
    {
        if (epfd_ != defaultepfd)
            close(epfd_);
    }

public:
    bool Create()
    {
        epfd_ = epoll_create(size);
        if (epfd_ < 0)
            return false;
        return true;
    }
    bool Addevent(int sock, uint32_t events)
    {
        // std::cout << "in Addevent" << std::endl;
        struct epoll_event ev;
        ev.data.fd = sock;
        ev.events = events;
        // std::cout << "ev.events: " << ev.events << " events: " << events << " out Addevent"<< std::endl;
        return epoll_ctl(epfd_, EPOLL_CTL_ADD, sock, &ev) == 0;
    }
    bool Delevent(int sock)
    {
        return epoll_ctl(epfd_, EPOLL_CTL_DEL, sock, nullptr) == 0;
    }
    int Wait(struct epoll_event revs[], int num, int timeout)
    {
        int n = epoll_wait(epfd_, revs, num, timeout);
        return n;
    }
    bool Control(int sock, uint32_t events, int op)
    {
        struct epoll_event ev;
        ev.data.fd = sock;
        ev.events = events;
        return epoll_ctl(epfd_, op, sock, &ev) == 0;
    }
    void Close()
    {
        if (epfd_ != defaultepfd)
            close(epfd_);
    }

private:
    int epfd_;
};